package com.symaster.common.geom;

import com.symaster.common.geom.entity.Polygon;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Collection;

/**
 * @author yinmiao
 * @version 2022-06-03 14:28
 */
public class ViewPolygon extends JFrame {

    private JScrollPane scrollPane;
    private MyPanel myPanel;

    public ViewPolygon() {
        initPage();
    }

    private void initPage() {
        setPreferredSize(new Dimension(700, 700));
        JPanel rootPanel = new JPanel();
        rootPanel.setLayout(new BorderLayout());
        scrollPane = new JScrollPane();
        rootPanel.add(scrollPane);
        setContentPane(rootPanel);
        pack();
    }

    public void setViewObj(ViewPolygonPanel panel) {
        this.myPanel = new MyPanel((int) panel.getWidth(), (int) panel.getHeight());
        this.myPanel.setPreferredSize(new Dimension((int) panel.getWidth(), (int) panel.getHeight()));
        this.scrollPane.setViewportView(myPanel);
        for (Polygon polygon : panel.getPolygons()) {
            myPanel.drawPolygon(polygon);
        }
    }

    public void open() {
        setVisible(true);
    }

    static class MyPanel extends JPanel {

        private Graphics imageGraphics;
        private Image imageCache;
        private final int imageWidth;
        private final int imageHeight;

        public MyPanel(int imageWidth, int imageHeight) {
            this.imageWidth = imageWidth;
            this.imageHeight = imageHeight;
        }

        private void clear() {
            this.imageCache = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
            this.imageGraphics = this.imageCache.getGraphics();
            this.imageGraphics.setColor(new Color(255, 255, 255));
            this.imageGraphics.fillRect(0, 0, imageWidth, imageHeight);
        }

        private void drawPolygon(Polygon p) {
            if (this.imageGraphics == null) clear();

            java.awt.Polygon polygon = p.toAwtPolygon();

            this.imageGraphics.setColor(new Color(80, 80, 80));
            this.imageGraphics.fillPolygon(polygon);

            this.imageGraphics.setColor(new Color(200, 50, 50));
            this.imageGraphics.drawPolygon(polygon);

            int[] xPoints = polygon.xpoints;
            int[] yPoints = polygon.ypoints;
            this.imageGraphics.setColor(new Color(80, 255, 80));
            for (int i = 0; i < xPoints.length; i++) {
                this.imageGraphics.drawRect(xPoints[i] - 1, yPoints[i] - 1, 3, 3);
            }
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            if (imageCache != null) {
                g.drawImage(imageCache, 20, 5, this);
            }
        }
    }
}